﻿using System;
using System.Collections.Generic;
using System.Linq;

using ApproveFlowEngine.Core.Base;

namespace ApproveFlowEngine.Core
{
    public class WorkFlowBuilder
    {
        public WorkFlowBuilder(int index, WorkFlowBuilder? parent)
        {
            Index = index;
            Parent = parent;
        }

        public WorkFlowBuilder(WorkNode data, int index, WorkFlowBuilder? parent)
        {
            Data = data;
            Index = index;
            Parent = parent;
        }

        private int Index { get; set; }
        private WorkFlowBuilder? Next { get; set; }
        private WorkNode Data { get; set; }
        private WorkFlowBuilder? Parent { get; set; }
        private List<WorkFlowBuilder> Childrens { get; set; } = new List<WorkFlowBuilder>();

        public WorkFlowBuilder AddChild(Action<WorkFlowBuilder> func)
        {
            var index = Childrens.Count + 1;
            var child = new WorkFlowBuilder(index, Parent);
            func(child);
            if (child.Data is null)
            {
                throw new Exception("添加子节点后请调用 SetNode 方法！");
            }
            var lastChild = Childrens.OrderBy(c => c.Index).LastOrDefault();
            if (lastChild is not null)
            {
                lastChild.Next = child;
            }
            Childrens.Add(child);

            return this;
        }

        public WorkFlowBuilder SetNode(WorkNode node)
        {
            Data = node;
            return this;
        }

        public WorkFlowBuilder AddNext(Func<WorkNode, WorkNode> func)
        {
            var index = Index + 1;
            var child = func(Data);
            var next = new WorkFlowBuilder(child, index, Parent);
            Next = next;
            return next;
        }
    }
}
